<template>
  <div class="app-wrapper app-table-wrapper">
    <div class="global-search-wrapper">
      <div class="search-item">
        <div class="left">
          <custom-button type="blue" :disabled="disabled" @click="updateIsFrozen(true)">冻结用户</custom-button>
          <custom-button type="green" :disabled="disabled" @click="updateIsFrozen(false)">解除冻结</custom-button>
        </div>
        <el-input
          v-model="keyword"
          class="primary-input margin-right-sm"
          placeholder="输入id/用户名/手机号/昵称"
          clearable
          @keydown.enter.stop="fetchData"
        ></el-input>
      </div>
    </div>
    <el-table class="margin-top-lg" border row-key="id" :data="data" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" />
      <el-table-column label="id" prop="id" align="center" />
      <el-table-column label="用户名" prop="username" align="center" />
      <el-table-column label="昵称" prop="nickName" align="center" />
      <el-table-column label="手机号" prop="phoneNumber" align="center" />
      <el-table-column label="注册时间" prop="createdAt" align="center" />
      <el-table-column label="最后登录时间" prop="latestLoginAt" align="center" />
      <el-table-column label="冻结" prop="isFrozen" align="center">
        <template #default="{ row }">
          <span>{{ row.isFrozen ? '是' : '否' }}</span>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-model:size="searchParams.pageSize"
      v-model:page="searchParams.pageIndex"
      class="margin-top-lg"
      :total="total"
      @pagination="fetchData"
    />
  </div>
</template>

<script lang="ts" setup>
import { fetchUsers, frozeUser, unFrozeUser, UserDataProps } from '@/service/user'
import { ElMessage } from 'element-plus'

const data = ref<UserDataProps[]>([])
const total = ref(0)
const keyword = ref('')
const selectRows = ref<UserDataProps[]>([])
const disabled = computed(() => selectRows.value.length === 0)

const searchParams = computed(() => ({
  pageIndex: 1,
  pageSize: 10,
  keyword: keyword.value
}))

onMounted(async () => {
  await fetchData()
})

async function fetchData() {
  const { list, count } = await fetchUsers(searchParams.value)
  data.value = list
  total.value = count
}

function handleSelectionChange(list: UserDataProps[]) {
  selectRows.value = [...list]
  console.log(selectRows.value)
}

async function updateIsFrozen(isFrozen = false) {
  const ids = selectRows.value
    .map(item => {
      return item.id
    })
    .join(',')
  if (isFrozen) {
    await frozeUser({ ids })
    ElMessage.success('冻结成功')
  } else {
    await unFrozeUser({ ids })
    ElMessage.success('解冻成功')
  }
  await fetchData()
}
</script>
<style lang="scss" scoped></style>
